package cn.itcast.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

import static cn.itcast.nio.c1.ByteBufferUtil.debugAll;


/**
 * @Author: LDeng
 * @Date: 2021-05-11 16:32
 */
@Slf4j
public class Server {

    private static void split(ByteBuffer source){
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            if(source.get(i)=='\n'){
                int length=i+1-source.position();
                ByteBuffer target=ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                debugAll(target);
            }
        }
        source.compact();
    }

    public static void main(String[] args) throws IOException {
        //1，创建Selector,管理多个channel
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        //2，建立selector和channel的联系（注册）
        //SelectionKey是将来事件发生后，通过selectionkey对象可以得到channel信息
        SelectionKey sscKey = ssc.register(selector, 0, null);
        //让sscKey只关注accept事件（accept,connect,read.write）
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        log.debug("register ServerSocketkey:{}", sscKey);

        ssc.bind(new InetSocketAddress(8080));
        while (true) {
            //3, select 方法, 没有事件发生，线程阻塞，有事件，线程才会恢复
            //事件发生后 ，要么处理，要么取消， 不能置之不理
            selector.select();
            //4， 处理事件,selectedKeys 内部包含了所有发生的事件
            Iterator<SelectionKey> iterator =
                    selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();//处理key以后要从selectedKeys集合中移除，
               // log.debug("客户端连接进来的Selectionkey:{}", key);
                //5， 区分事件类型
                if (key.isAcceptable()) {//如果是accept事件
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    //将byteBuffer作为附件关联到selectionKey上
                    ByteBuffer buffer = ByteBuffer.allocate(16);//attachment
                    SelectionKey sckey = sc.register(selector, 0, buffer);
                    sckey.interestOps(SelectionKey.OP_READ);
                    log.debug("客户端的SocketChannel:{}", sc);
                } else if (key.isReadable()) {//读取数据事件read
                    try {
                        SocketChannel channel = (SocketChannel) key.channel();//拿到触发事件的socketChannel
                        //取出上面附件中的Bytebuffer
                        ByteBuffer buffer = (ByteBuffer)key.attachment();
                        int read = channel.read(buffer);//如果是正常断开，read方法返回-1
                        if (read == -1) {
                            key.cancel();
                        } else {//处理读取的消息
                          split(buffer);
                          if(buffer.position()==buffer.limit()){
                              ByteBuffer newBuffer=ByteBuffer.allocate(buffer.capacity()*2);
                              buffer.flip();
                              newBuffer.put(buffer);
                              key.attach(newBuffer);
                          }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        log.debug("客户端强制关闭了连接....");
                        key.cancel();//从集合SelectedKey中删除这个key
                    }
                }

            }
        }


    }


}
